﻿using MediatR;
using Warehouse.Domain;
using Warehouse.Domain.DTO;
using Warehouse.Infrstructre.Interface;
using Warehouse.Read.API.Applcation.Command.WarehouseCommand;

namespace Warehouse.Read.API.Applcation.CommandHandlers.WarehouseCommandHandlers
{
    public class SelectWarehouseCommandHandlers : IRequestHandler<SelectWarehouseCommand, PageDTO<Warehouseinfo>>
    {

        private readonly IWarehouseRepository _warehouse;

        public SelectWarehouseCommandHandlers(IWarehouseRepository warehouse)
        {
            _warehouse = warehouse;
        }

        public async Task<PageDTO<Warehouseinfo>> Handle(SelectWarehouseCommand request, CancellationToken cancellationToken)
        {
            var list = (await _warehouse.GetAllAsyns()).Where(x => x.IsDel == false&&x.office_id==request.Oid);
            if (!string.IsNullOrEmpty(request.wareCode))
            {
                list = list.Where(x => x.WarehouseCode.Contains(request.wareCode)).ToList();
            }
            if (!string.IsNullOrEmpty(request.wareName))
            {
                list = list.Where(x => x.WarehouseName.Contains(request.wareName)).ToList();
            }
            if (!string.IsNullOrEmpty(request.type))
            {
                list = list.Where(x => x.WarehouseType.Contains(request.type)).ToList();
            }
            if (request.DpmId > 0)
            {
                list = list.Where(x => x.Department == request.DpmId).ToList();
            }
            //if (!string.IsNullOrEmpty(request.Oid))
            //{
            //    list = list.Where(x => x.office_id == request.Oid).ToList();
            //}
          

            PageDTO<Warehouseinfo> page = new PageDTO<Warehouseinfo>();

            page.Totalcount = list.Count();
            page.Pagecount = (int)Math.Ceiling(page.Totalcount * 1.0 / request.PageSize);
            page.list = list.OrderByDescending(x => x.WarehouseId).Skip((request.pageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();

            return page;


        }
    }
}
